package com.diudiutechnology.www.yadiudiu.util.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.diudiutechnology.www.yadiudiu.R;

import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2017/4/20.
 */

public class Sundry {
    /**
     * 对网络连接状态进行判断
     *
     * @return true, 可用； false， 不可用
     */
    public static boolean isOpenNetwork(Context mContext) {
        ConnectivityManager connManager = (ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connManager.getActiveNetworkInfo() != null) {
            return connManager.getActiveNetworkInfo().isAvailable();
        }

        return false;
    }
    //去掉 .\ufeff 前缀
    public static String JSONTokener(String in) {
        // consume an optional byte order mark (BOM) if it exists
        if (in != null && in.startsWith("\ufeff")) {
            in = in.substring(1);
        }
        return in;
    }
    /**
     * 替换指定范围内的字符串
     * @param start    开始索引
     * @param end      结束索引
     * @param source   原始字符串
     * @param replaceStr 替换字符串
     * @return
     */
    public static String replaceByIndexs(int start,int end,String source,String replaceStr){

        String returnString =source;
        if(source!=null && source.length()>0){
            String headString=source.substring(0,start-1);
            String contentString=replaceStr;
            String tailsString=source.substring(end,source.length());
            return headString+contentString+tailsString;
        }
        return returnString;
    }

    //轮播广告
    public static void initPointsLayout(LinearLayout dotLayout,Context mContext,int size,int pos) {
        dotLayout.removeAllViews();
        for (int i = 0; i < size; i++) {
            ImageView image = null;
            if (mContext != null) {
                image = new ImageView(mContext);
            }
            float denstity = mContext.getResources().getDisplayMetrics().density;
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    (int) (6 * denstity), (int) (6 * denstity));
            params.leftMargin = (int) (2 * denstity);
            params.rightMargin = (int) (2 * denstity);
            image.setLayoutParams(params);
            if (i == 0) {
                image.setBackgroundResource(R.drawable.shope);
            } else {
                if (pos==0){
                    image.setBackgroundResource(R.drawable.shapes);
                }else {
                    image.setBackgroundResource(R.drawable.shopes);
                }
                }

            dotLayout.addView(image);
        }
    }

    //轮播广告
    public static void refreshPoint(LinearLayout dotLayout,int position,int pos) {
        if (dotLayout != null) {
            for (int i = 0; i < dotLayout.getChildCount(); i++) {
                if (i == position) {
                    dotLayout.getChildAt(i).setBackgroundResource(
                    R.drawable.shope);
                  //  tv_content.setText(content[position]);
                } else {
                    if (pos==0){
                        dotLayout.getChildAt(i).setBackgroundResource(
                                R.drawable.shapes);
                    }else {
                        dotLayout.getChildAt(i).setBackgroundResource(
                                R.drawable.shopes);
                    }
                }
            }
        }
    }

//    //轮播广告 加文字
//    public static void refreshPoints(LinearLayout dotLayout, TextView tv_content, List <HF_homepagefragment_model> gethomresultA, int position, int pos) {
//        if (dotLayout != null) {
//            for (int i = 0; i < dotLayout.getChildCount(); i++) {
//                if (i == position) {
//                    dotLayout.getChildAt(i).setBackgroundResource(
//                            R.drawable.shope);
//                    tv_content.setText(gethomresultA.get(position).getPost_title());
//                } else {
//                    if (pos==0){
//                        dotLayout.getChildAt(i).setBackgroundResource(
//                                R.drawable.shapes);
//                    }else {
//                        dotLayout.getChildAt(i).setBackgroundResource(
//                                R.drawable.shopes);
//                    }
//                }
//            }
//        }
//    }
    public  static  StringBuilder getphon(String phone){
              /*号码出去前3位和后3位，中间补位用星号代替*/
        StringBuilder sb = new StringBuilder();
        if (!TextUtils.isEmpty(phone) && phone.length() > 6) {

            for (int i = 0; i < phone.length(); i++) {
                char c = phone.charAt(i);
                if (i >= 3 && i <= (phone.length()-4)) {
                    sb.append('*');
                } else {
                    sb.append(c);
                }
            }

        }
        return sb;
    }

    public  static  StringBuilder getsheng(String phone){
              /*号码出去前3位和后4位，中间补位用星号代替*/
        StringBuilder sb = new StringBuilder();
        if (!TextUtils.isEmpty(phone) && phone.length() > 14) {

            for (int i = 0; i < phone.length(); i++) {
                char c = phone.charAt(i);
                if (i >= 3 && i <= 14) {
                    sb.append('*');
                } else {
                    sb.append(c);
                }
            }

        }
        return sb;
    }
    //时间戳
    public static String getStrsTime(String cc_time) {
        String re_StrTime = null;
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
        long lcc_time = Long.valueOf(cc_time);
        re_StrTime = sdf.format(new Date(lcc_time * 1000L));
        return re_StrTime;
    }
    //时间戳
    public static String getStrTime(int pos ,String cc_time) {
        if (TextUtils.isEmpty(cc_time)){
            return "";
        }
        String re_StrTime = null;
        SimpleDateFormat sdf  = null;
        if (pos==0){
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }else if (pos==1){
            sdf = new SimpleDateFormat("yyyy-MM-dd");
        }else if (pos==2){
            sdf = new SimpleDateFormat("yyyy.MM.dd  HH:mm");
        }else if (pos==3){
            sdf = new SimpleDateFormat("yyyy.MM.dd");
        }else if (pos==4){
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        }
        long lcc_time = Long.valueOf(cc_time);
        re_StrTime = sdf.format(new Date(lcc_time * 1000L));
        return re_StrTime;
    }

    //时间戳
    public static String getStrTimes(String cc_time) {
        String re_StrTime = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        long lcc_time = Long.valueOf(cc_time);
        re_StrTime = sdf.format(new Date(lcc_time * 1000L));
        return re_StrTime;
    }
    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(String mobiles) {
    /*
    移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
    联通：130、131、132、152、155、156、185、186
    电信：133、153、180、189、（1349卫通）
    总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
    */
        String telRegex = "[1][3578]\\d{9}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobiles)) return false;
        else return mobiles.matches(telRegex);
    }
    //判断空
    public static boolean getStinges(String s) {

        if (s.equals("null")||s.equals("")||s==null){
            return true;
        }else{
            return false;
        }

    }
    /**
     * 判断字符串是否为空
     *
     * @param str
     * @return
     */
    public static boolean isEmpty(String str) {
        return str == null || str.trim().length() == 0;
    }
    public static File Imagecompression(Bitmap bitmap, String str){
        FileOutputStream fileOutStream = null;
        File filese=null;
        try {
            //通过相关方法生成一个Bitmap类型的对象
            filese=new File(Environment.getExternalStorageDirectory(),str);
            fileOutStream = new FileOutputStream(filese);
            bitmap.compress(Bitmap.CompressFormat.JPEG,100,fileOutStream); // 把位图输出到指定的文件中
            fileOutStream.flush();
            fileOutStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return filese;
    }
    //时间计算
    public static String showTime(String time) {
        System.out.println("timetimetimetimetimetimetime="+time);
        SimpleDateFormat sd_ymd_hms = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm");
        SimpleDateFormat sd_md_hms = new SimpleDateFormat("yyyyMMdd");
//        SimpleDateFormat sd_sh = new SimpleDateFormat("HH");
        try {
            Date date = sd_ymd_hms.parse(time);
            Calendar dat = Calendar.getInstance();
            dat.setTime(date);
            Calendar cNow = Calendar.getInstance();
            if (dat.get(Calendar.YEAR) == cNow.get(Calendar.YEAR)) {// 今年
                if (dat.get(Calendar.MONTH) == cNow.get(Calendar.MONTH)) {// 当月
                    if (dat.get(Calendar.DAY_OF_MONTH) == cNow
                            .get(Calendar.DAY_OF_MONTH)) {// 当天
                        if (dat.get(Calendar.HOUR_OF_DAY) == cNow
                                .get(Calendar.HOUR_OF_DAY)) {
                            int t = cNow.get(Calendar.MINUTE)- dat.get(Calendar.MINUTE) ;
                            if (t<= 1) {
                                return "刚刚";
                            } else {
                                return t+"分钟前";
                            }
                        } else {
                            return (cNow.get(Calendar.HOUR_OF_DAY)-dat.get(Calendar.HOUR_OF_DAY))+"小时以前";
                        }
                    } else {
//                        return getTimes(sd_md_hms.format(date));
                        return (cNow.get(Calendar.DAY_OF_MONTH)-dat.get(Calendar.DAY_OF_MONTH))+"天以前";
                    }
                } else {
                    // int datian=getTimes(sd_md_hms.format(date));
                    long datian=dateDiff(sd_md_hms.format(date));
                    System.out.println("datiandatiandatiandatian="+datian);
                    if (datian>=30){
                        return (cNow.get(Calendar.MONTH)-dat.get(Calendar.MONTH))+"个月以前";
                    }else {
                        return datian+"天以前";
                    }

                }

            } else {
                return (cNow.get(Calendar.YEAR)-dat.get(Calendar.YEAR))+"年以前";
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }
    public static long dateDiff(String startTime) {
        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH)+1;
        int dayr = c.get(Calendar.DAY_OF_MONTH);
        String daytime;
        if (month>=10){
            System.out.println("1");
            daytime=year+""+month+""+dayr;
        }else {
            System.out.println("2");
            daytime=year+"0"+month+""+dayr;
        }
        SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd");//输入日期的格式
        long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
        long nh = 1000 * 60 * 60;// 一小时的毫秒数
        long nm = 1000 * 60;// 一分钟的毫秒数
        long ns = 1000;// 一秒钟的毫秒数
        long diff;
        long day = 0;
        try {
            // 获得两个时间的毫秒时间差异
            diff = sd.parse(daytime).getTime()
                    - sd.parse(startTime).getTime();
            day = diff / nd;// 计算差多少天
            long hour = diff % nd / nh;// 计算差多少小时
            long min = diff % nd % nh / nm;// 计算差多少分钟
            long sec = diff % nd % nh % nm / ns;// 计算差多少秒
            // 输出结果
            System.out.println("时间相差：" + day + "天" + hour + "小时" + min
                    + "分钟" + sec + "秒。");
            if (day>=1) {
                return day;
            }else {
                if (day==0) {
                    return 1;
                }else {
                    return 0;
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;

    }
    //listview 与ScrollView冲突
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        ((ViewGroup.MarginLayoutParams)params).setMargins(10, 10, 10, 10);
        listView.setLayoutParams(params);
    }
    public static String stringFilter(String str){
        String regEx = "[^a-zA-Z\u4e00-\u9fa5]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("");
    }

    //加密MD5
    public static String getMD5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
//        String[] split = string.split("/");
//        string=split[0]+split[1];
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }
//身份证判断
    public static  boolean personIdValidation(String text) {
        String regx = "[0-9]{17}x";
        String reg1 = "[0-9]{15}";
        String regex = "[0-9]{18}";
        return text.matches(regx) || text.matches(reg1) || text.matches(regex);
    }
    // checkEmail判断邮箱格式
    public static boolean checkEmail(String email) {

        Pattern pattern = Pattern
                .compile("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\\.([a-zA-Z0-9_-])+)+$");
        Matcher matcher = pattern.matcher(email);
        if (matcher.matches()) {
            return true;
        }
        return false;
    }
    /**
     * 钱的展示
     * @param str
     * @return
     */
    public static String getmoyedouble1(String str){
        String qian="¥0.00元";

        if (TextUtils.isEmpty(str)){
            return qian;
        }
        double fla=Double.valueOf(str);
        DecimalFormat df = new DecimalFormat("0.00");
        String moye = df.format(fla);
        System.out.println("stringmd5result" + fla);
        //5==万，8==亿
        if (moye.length()<(5+3)){
            qian="¥"+moye+"元";
        }else if (moye.length()>=(5+3)){
            if(moye.length()<=(8+3)){
                double v = fla / 10000;
                BigDecimal bd= new BigDecimal(v);
                qian="¥"+bd.setScale(2,BigDecimal.ROUND_HALF_UP).toString()+"万元";
            } else if (moye.length()>(8+3)){
                double v = fla /100000000;
                BigDecimal bd= new BigDecimal(v);
                qian= "¥"+bd.setScale(2,BigDecimal.ROUND_HALF_UP).toString()+"亿元";
            }
        }
        return qian;
    }
    /**
     * 钱的展示
     * @param str
     * @return
     */
    public static String getmoyedouble1s(String str){
        String qian="¥0.00元/㎡";

        if (TextUtils.isEmpty(str)){
            return qian;
        }
        double fla=Double.valueOf(str);
        DecimalFormat df = new DecimalFormat("0.00");
        String moye = df.format(fla);
        System.out.println("stringmd5result" + fla);
        //5==万，8==亿
        if (moye.length()<(5+3)){
            qian="¥"+moye+"元/㎡";
        }else if (moye.length()>=(5+3)){
            if(moye.length()<=(8+3)){
                double v = fla / 10000;
                BigDecimal bd= new BigDecimal(v);
                qian="¥"+bd.setScale(2,BigDecimal.ROUND_HALF_UP).toString()+"万元/㎡";
            } else if (moye.length()>(8+3)){
                double v = fla /100000000;
                BigDecimal bd= new BigDecimal(v);
                qian= "¥"+bd.setScale(2,BigDecimal.ROUND_HALF_UP).toString()+"亿元/㎡";
            }
        }
        return qian;
    }
    public static String getorder(String str){
        String order="0";
        if (TextUtils.isEmpty(str)){
            return order;
        }
        double fla=Double.valueOf(str);
        System.out.println("stringmd5result" + fla);
        //5==万，8==亿
        if (str.length()<5){
            order=str;
        }else if (str.length()>=5){
            if(str.length()<=8){
                double v = fla / 10000;
                BigDecimal bd= new BigDecimal(v);
                order=bd.setScale(2,BigDecimal.ROUND_HALF_UP).toString()+"万";
            } else if (str.length()>8){
                double v = fla /100000000;
                BigDecimal bd= new BigDecimal(v);
                order= bd.setScale(2,BigDecimal.ROUND_HALF_UP).toString()+"亿";
            }
        }
        return order;
    }
    public static int cutStringToInt(String str, String cut) {
        int result = 0;
        if(cut == ""){
            result = Integer.parseInt(str);
        }else{
            int location = str.indexOf(cut);
            String newStr = str.substring(0, location);
            result = Integer.parseInt(newStr);
        }
        return result;
    }
}
